<template>
  <el-form label-width="auto" style="width: 1200px">
    <template>
      <el-form-item label="中文角色名称">
        <el-input v-model="form.nameZh" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="英文角色名称">
        <el-input v-model="form.nameEn" placeholder="请输入角色名称" />
      </el-form-item>
    </template>
    <el-form-item label="功能权限">
      <el-tree
        ref="treeRef"
        style="width: 100%"
        :data="functionDatas"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultExpendKeys"
      >
        <template #default="{ data }">
          <span v-if="data.level !== 3">{{ data.name }}</span>
          <!-- v-if="OperationControlArrayList[data.sequence] && OperationControlArrayList[data.sequence].children" -->
          <div class="checkBoxGroup" style="margin: 0px 10px; position: absolute; right: 0px">
            <el-checkbox-group style="width: 100%" v-model="operationcontrol">
              <template v-for="item in operateDataArr(data)" :key="item.id">
                <el-checkbox
                  :label="item?.name"
                  size="small"
                  :value="item?.id"
                  style="margin-right: 10px"
                  v-if="item?.level === 3"
                  :disabled="setDisabled(item)"
                  @click.stop
                />
              </template>
            </el-checkbox-group>
          </div>
        </template>
      </el-tree>
    </el-form-item>
    <el-form-item>
      <div class="flex justify-center w-full">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="ElMessageBox.close()">关闭</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { onBeforeMount, reactive, ref } from 'vue'
// import { functionData, operateData } from './data'
import { flatArrFunGetThird, flatArrFunO } from '../action'
import { systemManageApi } from '@/api/modules/systemManage'
import type { PropType } from 'vue'
import mittBus from '@/utils/mittBus'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  row: Object as PropType<any>,
  action: String
})
const defaultProps = {
  children: 'children',
  label: 'name'
}
const form = reactive({
  nameZh: '',
  nameEn: '',
  roleId: ''
})
const OperationControlArrayList = ref()
const defaultCheckedKeys = ref()
const operationcontrol = ref<Array<string>>([])
const flatOpearationData = ref()
const treeRef = ref()
const functionDatas = ref()
const operateDatas = ref()
const operateDataArr = (data: any) => {
  // 扁平化store数组,过滤当前展示的数据
  const res = flatOpearationData.value.filter(item => {
    return item.id === data.id
  })
  if (res.length > 0) return res[0].children
}
const setDisabled = data => {
  let state = false
  if (treeRef.value) {
    const selectOperateArr = treeRef.value!.getCheckedKeys(false, false) // 当前选择的功能
    const res = selectOperateArr.filter(item => {
      return Number(item) === Number(data.parentId)
    })
    if (res.length > 0) {
      state = false
    } else {
      state = true
    }
  }
  return state
}

const onSubmit = async () => {
  const keysArr = treeRef.value!.getCheckedNodes(false, true).map(item => item.id)
  const functionArr = operationcontrol.value.concat(keysArr)
  const numFunctionArr = functionArr.map(item => Number(item))
  const params = {
    functionList: numFunctionArr,
    nameEn: form.nameEn,
    nameZh: form.nameZh
  }
  if (props.action === 'add') {
    const res: any = await systemManageApi.addRole(params)
    if (res.code === 200) {
      ElMessage.success('新建成功')
      mittBus.emit('refreshRoleList')
      ElMessageBox.close()
    } else {
      ElMessage.error('新建失败')
    }
  } else {
    if (props.action === 'edit') {
      Object.assign(params, { roleId: props.row!.roleId })
    } else if (props.action === 'set') {
      Object.assign(params, { roleId: form.roleId })
    }
    const res: any = await systemManageApi.editRole(params)
    if (res.code === 200) {
      ElMessage.success('编辑成功')
      if (props.action === 'edit') {
        mittBus.emit('refreshRoleList')
      }
      ElMessageBox.close()
    } else {
      ElMessage.error('编辑失败')
    }
  }
}
const checkChildren = arr => {
  arr.forEach(item => {
    if (item.children) {
      if (item.level === 2) {
        item.children = []
      } else {
        checkChildren(item.children)
      }
    }
  })
  return arr
}
const defaultExpendKeys = ref<string[]>([])
const treeData = ref()
const getDefaultLimit = async (res, roleId) => {
  // 编辑时，调个接口拿当前角色有权限的id,然后赋值给两个v-model的字段，使其初始默认勾选
  const { data } = await systemManageApi.getFunctionList({ roleId })
  const functionlist = data.map(item => String(item))
  const thirdArr = flatArrFunGetThird(JSON.parse(JSON.stringify(res.data)))
  const idArr: string[] = []
  thirdArr.forEach((item: any) => {
    if (item.level === 3) {
      idArr.push(item.id)
    }
  })
  const filterArr = functionlist.filter(value => idArr.includes(value))
  // 再拿除此之外的数据
  const filterModuleArr1 = functionlist.filter(value => !idArr.includes(value))
  const filterModuleArr = filterModuleArr1.filter(item => {
    return item !== '1' && item !== '2' && item !== '3'
  })
  defaultCheckedKeys.value = filterModuleArr
  operationcontrol.value = filterArr
  defaultExpendKeys.value = filterModuleArr
  treeRef.value.setCheckedKeys(filterModuleArr)
  if (props.action !== 'set') {
    form.nameEn = props.row?.nameEn!
    form.nameZh = props.row?.nameZh!
  }
}
onBeforeMount(() => {
  if (props.action === 'set') {
    systemManageApi.getFunctionTree().then(async (res: any) => {
      treeData.value = res
      operateDatas.value = JSON.parse(JSON.stringify(res.data))
      functionDatas.value = checkChildren(JSON.parse(JSON.stringify(res.data)))
      flatOpearationData.value = flatArrFunO(operateDatas.value)
      OperationControlArrayList.value = operateDatas.value
      if (props.action === 'edit' || props.action === 'set') {
        let roleId: any
        if (props.action === 'edit') {
          roleId = props.row!.roleId
        }
        getDefaultLimit(res, roleId)
      }
    })
  } else {
    systemManageApi.getFunctionTree().then(async (res: any) => {
      treeData.value = res
      operateDatas.value = JSON.parse(JSON.stringify(res.data))
      functionDatas.value = checkChildren(JSON.parse(JSON.stringify(res.data)))
      flatOpearationData.value = flatArrFunO(operateDatas.value)
      OperationControlArrayList.value = operateDatas.value
      if (props.action === 'edit' || props.action === 'set') {
        let roleId: any
        if (props.action === 'edit') {
          roleId = props.row!.roleId
        }
        getDefaultLimit(res, roleId)
      }
    })
  }
})
</script>
<style scoped lang="scss"></style>
